<script setup lang="tsx">
import { ref } from 'vue';
import { NButton } from 'naive-ui';
import { fetchBatchDeleteRole, fetchDeleteRole, fetchGetRoleList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import TableHeaderOperation from '@/components/advanced/table-header-operation.vue';
import RoleOperateModal from './modules/role-operate-modal.vue';
import RoleSearch from './modules/role-search.vue';
import MenuAuthModal from './modules/menu-auth-modal.vue';

const appStore = useAppStore();

const { columns, columnChecks, data, loading, getData, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetRoleList,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    roleId: null,
    status: null,
    roleName: null,
    roleKey: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'roleId',
      title: $t('page.manage.role.roleId'),
      width: 64,
      align: 'center'
    },
    {
      key: 'roleName',
      title: $t('page.manage.role.roleName'),
      align: 'center',
      minWidth: 200
    },
    {
      key: 'roleKey',
      title: $t('page.manage.role.roleKey'),
      align: 'center',
      minWidth: 200
    },
    {
      key: 'roleDesc',
      title: $t('page.manage.role.roleDesc'),
      minWidth: 200
    },
    {
      key: 'status',
      title: $t('page.manage.role.roleStatus'),
      align: 'center',
      width: 200,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const switchMap: Record<Api.Common.EnableStatus, boolean> = {
          1: true,
          2: false
        };
        return <n-switch v-model:value={switchMap[row.status]} disabled />;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 360,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.roleId)}>
            {$t('common.edit')}
          </NButton>
          <NButton type="info" ghost size="small" onClick={() => openMenuAuth(row.roleId)}>
            {$t('page.manage.role.menuAuth')}
          </NButton>
          <NButton type="error" ghost size="small" onClick={() => showDeleteConfirm(row.roleId)}>
            {$t('common.delete')}
          </NButton>
        </div>
      )
    }
  ]
});

const { modalVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
  useTableOperate(data, getData);

// 菜单权限管理相关状态
const menuAuthModalVisible = ref(false);
const selectedRoleId = ref<number>(0);

async function handleBatchDelete() {
  try {
    const roleIds = checkedRowKeys.value.map(key => Number(key)).filter(id => !Number.isNaN(id));
    const result = await fetchBatchDeleteRole(roleIds);
    if (!result.error) {
      window.$message?.success($t('common.deleteSuccess'));
      await onBatchDeleted();
    } else {
      window.$message?.error(result.error.message || $t('common.operationFailed'));
    }
  } catch (error) {

    window.$message?.error($t('common.operationFailed'));
  }
}

async function handleDelete(id: number) {
  try {
    const result = await fetchDeleteRole(id);
    if (!result.error) {
      window.$message?.success($t('common.deleteSuccess'));
      await onDeleted();
    } else {
      window.$message?.error(result.error.message || $t('common.operationFailed'));
    }
  } catch (error) {

    window.$message?.error($t('common.operationFailed'));
  }
}

// 显示删除确认对话框
function showDeleteConfirm(id: number) {
  window.$dialog?.warning({
    title: $t('common.tip'),
    content: $t('common.confirmDelete'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: () => {
      handleDelete(id);
    }
  });
}

function edit(id: number) {
  handleEdit(id);
}

// 打开菜单权限管理弹窗
function openMenuAuth(id: number) {
  selectedRoleId.value = id;
  menuAuthModalVisible.value = true;
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RoleSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
    <NCard :title="$t('page.manage.role.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :show-delete="true"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="866"
        :loading="loading"
        remote
        :row-key="row => row.roleId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <RoleOperateModal
        v-model:visible="modalVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
      <MenuAuthModal v-model:visible="menuAuthModalVisible" :role-id="selectedRoleId" @submitted="getData" />
    </NCard>
  </div>
</template>

<style scoped></style>
